const yapi = require('../yapi.js');
const baseModel = require('./base.js');

class dubboProjectModel extends baseModel {
  getName() {
    return 'dubboProject';
  }

  constructor(){
    super();
    this.handleEnvNullData = this.handleEnvNullData.bind(this)
  }

  getSchema() {
    return {
      cnname: { type: String, required: true },
      enname: { type: String, required: true },
      desc: String,
      groupid: { type: Number, required: true },
      projecttype: { type: String, required: true, enum: ['public', 'private'] },
      userlist: [
        {
          userid: Number,
          role: { type: Number, enum: [0, 1, 2] },
          username: String,
          rtxno: String,
          cname:String
        }
      ],
      icon: String,
      color: String,
      ctime: Number,
      etime: Number,
      cuserid: { type: Number, required: true },
      euserid: { type: Number, required: true },
      onlinedate: String,
      //ttc: 新增expname和childbase字段
      expname:String,
      childbase:String,
      status: { type: Number, required: true, enum: [1, 2, 3, 4] },
      batch: { type: Number, default: 1 },
      dgroup: String,
      evnconfig: [
        {cname: String, dubbourl: String}
        ]
    };
  }

  updateMember(data) {
    return this.model.update(
      {
        'userlist.userid': data.userid
      },
      {
        $set: {
          'userlist.$.username': data.username,
          'userlist.$.rtxno': data.rtxno,
          'userlist.$.cname': data.cname
        }
      }
    );
  }

  save(data) {
    let m = new this.model(data);
    return m.save();
  }

  handleEnvNullData(data){
    data = data.toObject();
    data.toObject = ()=> data;
    let isFix = false;
    if(Array.isArray(data.evnconfig)){
      data.evnconfig = data.evnconfig.map(item=>{
        item.global = item.global.filter(g=>{
          if(!g || typeof g !== 'object'){
            isFix = true;
            return false;
          }
          return true;
        });
        return item;
      })
    }

    if(isFix){
      this.model.update(
        {
          _id: data._id

        },
        {
          $set: { evnconfig: data.evnconfig }
        },
        { runValidators: true }
      );
    }
    return data;
  }

  get(id) {
    return this.model
      .findOne({
        _id: id
      })
      .exec()
  }

  getByEnv(id) {
    return this.model
      .findOne({
        _id: id
      })
      .select('evnconfig')
      .exec();
  }

  getProjectWithAuth(group_id, uid) {
    return this.model.countDocuments({
      groupid: group_id,
      'userlist.userid': uid
    });
  }

  getBaseInfo(id, select) {
    select =
      select ||
        '_id batch cnname enname desc groupid dgroup color icon onlinedate expname childbase cuserid euserid ctime etime userlist projecttype status evnconfig';
    return this.model
      .findOne({
        _id: id
      })
      .select(select)
      .exec()
  }

  getByDomain(domain) {
    return this.model
      .find({
        prd_host: domain
      })
      .exec()
  }

  getByName(id) {
    return this.model
      .findOne({
        _id: id
      })
      .select('dgroup')
      .exec()
  }

  checkNameRepeat(cnname, groupid) {
    return this.model.countDocuments({
      cnname: cnname,
      groupid: groupid
    });
  }

  checkDomainRepeat(domain, basepath) {
    return this.model.countDocuments({
      prd_host: domain,
      basepath: basepath
    });
  }

  list(group_id) {
    let params = { groupid: group_id };
    return this.model
      .find(params)
      .select(
        '_id batch cnname enname desc groupid bgroup color icon onlinedate cuserid euserid ctime etime userlist projecttype status evnconfig'
      )
      .sort({ _id: -1 })
      .exec();
  }

  // 获取项目数量统计
  getProjectListCount() {
    return this.model.countDocuments();
  }

  countWithPublic(group_id) {
    let params = { group_id: group_id, project_type: 'public' };
    return this.model.countDocuments(params);
  }

  listWithPaging(group_id, page, limit) {
    page = parseInt(page);
    limit = parseInt(limit);
    return this.model
      .find({
        group_id: group_id
      })
      .sort({ _id: -1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .exec();
  }

  listCount(group_id) {
    return this.model.countDocuments({
      group_id: group_id
    });
  }

  countByGroupId(group_id) {
    return this.model.countDocuments({
      groupid: group_id
    });
  }

  del(id) {
    return this.model.remove({
      _id: id
    });
  }

  delByGroupid(groupId) {
    return this.model.remove({
      groupid: groupId
    });
  }

  up(id, data) {
    data.up_time = yapi.commons.time();
    return this.model.update(
      {
        _id: data.id ? data.id : id
      },
      data,
      { runValidators: true }
    );
  }

  addMember(id, data) {
    return this.model.update(
      {
        _id: id
      },
      {
        // $push: { members: data }
        $push: { userlist: { $each: data } }
      }
    );
  }

  delMember(id, uid) {
    return this.model.update(
      {
        _id: id
      },
      {
        $pull: { userlist: { userid: uid } }
      }
    );
  }

  checkMemberRepeat(id, uid) {
    return this.model.countDocuments({
      _id: id,
      'userlist.userid': uid
    });
  }

  changeMemberRole(id, uid, role) {
    return this.model.update(
      {
        _id: id,
        'userlist.userid': uid
      },
      {
        $set: { 'userlist.$.role': role }
      }
    );
  }

  // changeMemberEmailNotice(id, uid, notice) {
  //   return this.model.update(
  //     {
  //       _id: id,
  //       'userlist.': uid
  //     },
  //     {
  //       $set: { 'members.$.email_notice': notice }
  //     }
  //   );
  // }

  search(keyword) {
    return this.model
      .find({
        name: new RegExp(keyword, 'ig')
      })
      .limit(10);
  }
}

module.exports = dubboProjectModel;
